package com.jplus.core.plugin.async;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.anno.boot.Configuration;
import com.jplus.core.anno.com.Autowired;
import com.jplus.core.anno.com.Order;
import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.proxys.Proxy;
import com.jplus.core.core.proxys.ProxyChain;
import com.jplus.core.utill.JUtil;

/**
 * 线程池代理
 */
@Configuration
@Order(1)
public class AsyncConfigurationProxy implements Proxy {

	private final Logger log = LoggerFactory.getLogger(AsyncConfigurationProxy.class);
	private @Autowired ApplicationContext context;

	@Override
	public Object doProxy(final ProxyChain proxyChain) throws Throwable {
		boolean async = false;
		String executor = null;
		Class<?> c = proxyChain.getTargetClass();
		if (c.isAnnotationPresent(Async.class)) {// 判断类
			executor = c.getAnnotation(Async.class).value();
			async = true;
		} else {// 判断方法
			Method m = proxyChain.getTargetMethod();
			if (m.isAnnotationPresent(Async.class)) {
				executor = m.getAnnotation(Async.class).value();
				async = true;
			}
		}
		if (async) {// 确认使用线程池
			Thread threadOne = getOneThread(proxyChain);
			if (JUtil.isEmpty(executor)) {
				threadOne.start();
			} else {
				Executor obj = (Executor) context.getBean(executor);
				obj.execute(threadOne);
			}
			return null;
		} else { // 不适用线程异步
			return proxyChain.doProxyChain();
		}
	}

	/**
	 * 临时获取一个线程类
	 */
	private Thread getOneThread(final ProxyChain proxyChain) {
		Thread t = new Thread() {
			@Override
			public void run() {
				try {
					proxyChain.doProxyChain();
				} catch (Throwable e) {
					log.info("ProxyAsync ERROR:" + e);
				}
			}
		};
		t.setDaemon(true);
		return t;
	}

}
